<template>
  <NvCrud v-model:form="form" :option :data @row-update="handleSave" />
</template>

<script setup lang="ts">
import type { NvCrudOption, NvOption } from 'nv-crud'
import { NvCrud } from 'nv-crud'
import { ref } from 'vue'

interface Data { id?: number, name?: string, province?: string, city?: string, area?: string }

const form = ref<Data>({})

const data = ref<Data[]>([
  { id: 1, name: '张三', province: '510000', city: '510100', area: '510122' },
  { id: 2, name: '李四', province: '530000', city: '530100', area: '530124' },
])

function handleSave(done: (close: boolean) => void) {
  setTimeout(() => {
    const idx = data.value.findIndex(item => item.id === form.value.id)
    if (idx > -1) {
      data.value[idx] = form.value
    }
    done(true)
  }, 1000)
}

const baseUrl = 'https://api.avuejs.com/area'
const option: NvCrudOption<Data> = {
  actionbar: false,
  toolbar: false,
  fields: {
    name: {
      title: '姓名',
    },
    province: {
      title: '省份',
      type: 'select',
      dict: [
        { label: '四川省', value: '510000' },
        { label: '云南省', value: '530000' },
      ],
    },
    city: {
      title: '城市',
      type: 'select',
      dict: (row) => {
        const cities: Record<string, NvOption[]> = {
          510000: [
            { label: '成都市', value: '510100' },
            { label: '绵阳市', value: '510700' },
          ],
          530000: [
            { label: '昆明市', value: '530100' },
            { label: '曲靖市', value: '530300' },
          ],
        }
        return cities[row.province!]
      },
    },
    area: {
      title: '地区',
      type: 'select',
      dict: row => `${baseUrl}/getArea/${row.city}`,
      props: {
        valueField: 'code',
        labelField: 'name',
      },
    },
  },
}
</script>
